package edu.yuhf.pac;

import java.util.LinkedList;

//仓库 
public class Storage {
	public final int MAX_NUM=100;
	LinkedList<Product> list =new LinkedList<>();
	 
	public void produce( int number) {
		synchronized (list){					//给list方法加锁
			while(list.size()+number>=MAX_NUM) {
				System.out.println("仓库已满，无法生产"+number+"产品");
				try {
					list.wait();				//挂起线程 释放锁
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			for(int i=0;i<number;i++) {
				list.add(new Product(i,Thread.currentThread().getName()+"_"+i));
			}
			System.out.println("已经生产了"+number+"件产品,仓库中共有"+list.size()+"件产品");
			list.notifyAll();					//唤醒在此对象等待池中等待的所有线程
		}
	}
	public void buy( int number) {
		synchronized(list) {
			while(list.size()-number<=0) {
				System.out.println("仓库存货不足，无法消费"+number+"件产品");
				try {
					list.wait();				//挂起线程 释放锁
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}	
			}
			for( int i=0;i<number;i++) {
				list.remove();
			}
			System.out.println("已经销费了"+number+"件产品，仓库中还有"+list.size()+"件产品");
			list.notifyAll();
		}
		
	}
}
